package com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.proof.face

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication

import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.IApiProcessCameroonCallback
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.createApiActionCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.doPostRequestCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.doUploadImageCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.user.mainProcessFormatCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.utils.imageUtil.ImageConvert
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

class ProofCameroonFaceViewModel : ViewModel() {

    private val _loadingResult = MutableLiveData<Boolean>()
    val loadingResult: LiveData<Boolean> = _loadingResult

    private val _pageDetailResult = MutableLiveData<ProofCameroonFaceTypeResult>()
    val pageDetailResult: LiveData<ProofCameroonFaceTypeResult> = _pageDetailResult

    private val _mainProcessResult = MutableLiveData<ProofCameroonFaceMainProcessResult>()
    val mainProcessResult: LiveData<ProofCameroonFaceMainProcessResult> = _mainProcessResult

    private val _nextRouterResult =
        MutableLiveData<ProofCameroonFaceNextRouterResult<AppCompatActivity>>()
    val nextRouterResult: LiveData<ProofCameroonFaceNextRouterResult<AppCompatActivity>> =
        _nextRouterResult

    /** 查询主流程接口 */
    fun mainProcess() {
        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiActionCameroon()
        action["path"] = "D50PrK3UELaosdHcVCL7A"

        context.doPostRequestCameroon(action, object : IApiProcessCameroonCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false
                val obj = jsonObject.optJSONObject("obj")
                _mainProcessResult.value = ProofCameroonFaceMainProcessResult(success = obj)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false
                _mainProcessResult.value =
                    ProofCameroonFaceMainProcessResult(error = errMsg)
            }
        })
    }

    /**
     * 上传图片
     */
    private fun uploadImage(filePath: String, type: Int = 2) {
        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>()
        action["filePath"] = filePath
        action["cardType"] = "FACE"

        context.doUploadImageCameroon(action, object : IApiProcessCameroonCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false
                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                val url = obj.optString("url")
                if (url.isNotBlank()) {
                    uploadImageResult(url, type)
                } else {
                    uploadImageResult(null, type)
                }
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false
                uploadImageResult(null, type, errMsg)
            }
        })
    }

    /**
     * 启动人脸检测
     */
    fun startFaceDetecting() {
        val facePicUrl = _pageDetailResult.value?.facePicUrl ?: ""
        val facePicPath = _pageDetailResult.value?.facePicPath
        val facePicBitmap = _pageDetailResult.value?.facePicBitmap

        if (facePicUrl.isBlank()) {
            _pageDetailResult.value = ProofCameroonFaceTypeResult(
                facePicUrl = facePicUrl,
                facePicPath = facePicPath,
                facePicBitmap = facePicBitmap,
                startFaceDetect = true
            )
            return
        }

        saveFaceInfo()
    }

    /**
     * 保存face信息
     */
    fun saveFaceInfo() {
        _loadingResult.value = true
        val facePicUrl = _pageDetailResult.value?.facePicUrl ?: ""
        if (facePicUrl.isBlank()) {
            _loadingResult.value = false
            _mainProcessResult.value =
                ProofCameroonFaceMainProcessResult(error = "Please upload the selfie picture")
            return
        }

        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiActionCameroon()
        action["path"] = "lslb0UDLLZQxmdjHjfA"
        action["faceImgUrl"] = facePicUrl
        action["cardType"] = "FACE"

        context.doPostRequestCameroon(action, object : IApiProcessCameroonCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false
                mainProcess()
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false
                _mainProcessResult.value =
                    ProofCameroonFaceMainProcessResult(error = errMsg)
            }
        })
    }

    /** 页面跳转 */
    fun nextRouter(jsonObject: JSONObject) {
        // 判断下一步
        val nextRouterResult = jsonObject.mainProcessFormatCameroon(fromProof = true)
        if (nextRouterResult.nextRouter != null) {
            _nextRouterResult.value =
                ProofCameroonFaceNextRouterResult(nextPage = nextRouterResult.nextRouter)
        }
    }

    /**
     * 处理图片uri
     */
    @SuppressLint("Recycle")
    fun handlePickImageResult(context: Context, result: Uri?) {
        try {
            println(result.toString())
            result?.let {
                val path = imageUriToLocalFile(context, it)
                //压缩图片
                ImageConvert.startConvertImage(File(path)) { localPath, thumpImg ->
                    updateImageResult(localPath, thumpImg)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 处理图片path
     */
    fun handleTakePictureResult(result: String?) {
        try {
            println(result.toString())
            result?.let {
                val localPath = it
                val thumpImg = imagePathToBitmap(localPath)
                updateImageResult(localPath, thumpImg)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 上传图片回显
     */
    private fun uploadImageResult(url: String?, type: Int = 2, error: String? = null) {
        try {
            val facePicUrl = url
            var facePicPath = _pageDetailResult.value?.facePicPath
            var facePicBitmap = _pageDetailResult.value?.facePicBitmap

            if (url == null) {
                facePicPath = null
                facePicBitmap = null
            }

            _pageDetailResult.value = ProofCameroonFaceTypeResult(
                facePicUrl = facePicUrl,
                facePicPath = facePicPath,
                facePicBitmap = facePicBitmap,
                error = error
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 更新图片显示
     */
    private fun updateImageResult(localPath: String, thumpImg: Bitmap) {
        try {
            var facePicUrl = _pageDetailResult.value?.facePicUrl
            _pageDetailResult.value = ProofCameroonFaceTypeResult(
                type = 0,
                facePicUrl = facePicUrl,
                facePicPath = localPath,
                facePicBitmap = thumpImg
            )

            // 上传图片
            uploadImage(localPath)

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun imageUriToLocalFile(
        context: Context,
        contentURI: Uri
    ): String {
        try {
            println(contentURI.path)

            val imgDir = "${
                ProjectApplication.context.applicationContext.filesDir
            }${File.separator}${ProjectApplication.mProduct}_IAGS"

            val dirFile = File(imgDir)
            if (!dirFile.exists()) {
                dirFile.mkdirs()
            }

            val outFilePath = "$imgDir/${System.currentTimeMillis()}.jpg"
            val imgInputStream: InputStream =
                context.contentResolver.openInputStream(contentURI) ?: return ""
            val outFile = File(outFilePath)
            val buffer = ByteArray(1024)
            var len: Int
            val fos = FileOutputStream(outFile)
            while (imgInputStream.read(buffer).also { len = it } != -1) {
                fos.write(buffer, 0, len)
            }
            fos.flush()
            fos.close()
            imgInputStream.close()
            return outFilePath
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    fun imagePathToBitmap(filePath: String?): Bitmap {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = false
        return BitmapFactory.decodeFile(filePath, options)
    }
}